
<h1>模特训练</h1>
<div>
<input type="file" id="audioFile" accept=".wav">
    <button onclick="uploadFile()">上传文件</button></div>
<br>
<div>
<label for="taskCodeBox">文件名：</label>
<input type="text" id="taskCodeBox" readonly style="width: 300px;">
</div>
<br>
<div>
<button onclick="callPreprocessAndTran()">调用预处理接口</button></div>


<div>返回结果:</div>
<div>
<label for="taskCodeBox">返回结果1：</label>
<input type="text" id="taskCodeBox11" readonly style="width: 300px;">
</div>

<div>
<label for="taskCodeBox">返回结果2：</label>
<input type="text" id="taskCodeBox22" readonly style="width: 300px;">

<h1>音频合成工具</h1>
<div class="container">
        <div>
            <label for="text">合成文本：</label>
            <textarea id="text" rows="5" placeholder="请输入要合成的文本内容"></textarea>
        </div>
        <button id="synthesizeBtn" onclick="handleSynthesis()">合成音频</button>
        <div id="status"></div>
        <audio id="audioPlayer" controls></audio>
</div>

<h1>这个页面上的所有框都必须要有，但是可以隐藏它们(也可以修改CSS)</h1>
<div><b>1.模特训练 选择一个.wav视频 点击上传即可   </div> </b> <br>
<div><b>2.  点击“调用预先处理接口”等待响应 </div> </b> <br>
    <img src="{{ url_for('static', filename='images/22.png') }}" alt="图片1" width="800" height="400">
<div><b>3.输入文本，之后点击合成音频，等待响应  </div> </b> <br>
        <img src="{{ url_for('static', filename='images/33.png') }}" alt="图片1" width="800" height="400">
<script>
async function uploadFile() {
  const fileInput = document.getElementById("audioFile");
  const fileNameDisplay = document.getElementById("fileName");

  if (!fileInput.files.length) {
    alert("请选择一个 WAV 文件！");
    return;
  }

  const file = fileInput.files[0];
  const formData = new FormData();
  formData.append("file", file);

  try {
    const response = await fetch("http://127.0.0.1:5000/api/uploads", {
      method: "POST",
      body: formData
    });

    if (!response.ok) {
      const text = await response.text();
      alert("上传失败：" + text);
      return;
    }

    const data = await response.json();
    alert("上传成功！文件路径：" + data.file_path);

      // 显示后端返回的文件名到只读输入框
    taskCodeBox.value = data.file_path;



  } catch (err) {
    alert("上传请求出错：" + err.message);
  }
}


let preprocessResult = null;

async function callPreprocessAndTran(){

  const taskCodeBox = document.getElementById('taskCodeBox');
  const referenceAudioPath = taskCodeBox.value.trim();

    if (!referenceAudioPath) {
    alert("请先上传文件，文件名不能为空");
    return;
  }

  const payload = {
    format: "wav",
    reference_audio: referenceAudioPath,
    lang: "zh"

  };

  try {
    const response = await fetch("http://127.0.0.1:18180/v1/preprocess_and_tran", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    });

    console.log("请求体:", payload);

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }

    const data = await response.json();
    preprocessResult = data;  // 保存返回结果
    console.log("预处理结果:", preprocessResult);

  // 显示结果
    document.getElementById('taskCodeBox11').value = data.asr_format_audio_url || '';
    document.getElementById('taskCodeBox22').value = data.reference_audio_text || '';
    return data;

  } catch (err) {
    console.error("接口调用失败:", err);
    throw err;
  }
}


async function handleSynthesis() {
    console.log("开始合成")
    const btn = document.getElementById('synthesizeBtn');
    const text = document.getElementById('text').value;
    const statusDiv = document.getElementById('status');
    const audioPlayer = document.getElementById('audioPlayer');
    const referenceAudio = document.getElementById('taskCodeBox11').value;
    const referenceText = document.getElementById('taskCodeBox22').value;
    console.log(referenceAudio)
    console.log(referenceText)

            // 验证输入
            if (!text || !referenceAudio || !referenceText) {
                statusDiv.className = 'error';
                alert('请填写所有必填字段！')
                return;
            }

            try {
                // 禁用按钮并显示加载状态
                btn.disabled = true;
                statusDiv.className = 'loading';
                statusDiv.textContent = '正在合成音频，请稍候...';
                audioPlayer.src = '';

                // 生成UUID
                const speakerId = crypto.randomUUID();
                console.log(speakerId)

                // 准备请求数据
                const payload = {
                    speaker: speakerId,
                    text: text,
                    format: "wav",
                    topP: 0.7,
                    max_new_tokens: 1024,
                    chunk_length: 100,
                    repetition_penalty: 1.2,
                    temperature: 0.7,
                    need_asr: false,
                    streaming: false,
                    is_fixed_seed: 0,
                    is_norm: 0,

                    reference_audio: referenceAudio,
                    reference_text: referenceText
                };

                // 发送请求
                const response = await fetch('http://127.0.0.1:18180/v1/invoke', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(payload)
                });

                if (!response.ok) {
                    throw new Error(`请求失败: ${response.status}`);
                }

                // 获取音频数据
                const audioBlob = await response.blob();
                const audioUrl = URL.createObjectURL(audioBlob);

                // 播放音频
                audioPlayer.src = audioUrl;

                statusDiv.className = 'success';
                statusDiv.textContent = '音频合成成功！';

            } catch (error) {
                statusDiv.className = 'error';
                statusDiv.textContent = `合成失败: ${error.message}`;
                console.error('合成错误:', error);
            } finally {
                // 无论成功失败都重新启用按钮
                btn.disabled = false;
            }
        }
</script>
